const express = require('express');
const { Op } = require('sequelize');
const router = express.Router();
const { success, failure } = require('../../utils/responses');
const { settingsFilterBody } = require('../../utils/filter-req');
const { NotFound } = require('http-errors');
const { setKey, getKey } = require('../../utils/redis');
const { delKey } = require('../../utils/redis');
const { Setting, Course, Chapter } = require('../../models');
const { coursesIndex, chaptersIndex } = require('../../utils/meilisearch');
const getList = async () => {
  const setting = await Setting.findOne();
  if (!setting) {
    throw new NotFound('初始系统设置未找到，请运行种子文件。');
  }
  return setting;
};
router.get('/', async (req, res) => {
  try {
    // 缓存的 key，定义为：setting
    const cacheKey = 'setting';

    // 读取缓存中的数据
    let settings = await getKey(cacheKey);
    // 如果缓存中没有数据，则从数据库中读取数据
    if (!settings) {
      settings = await Setting.findAll();
      if (!settings) {
        throw new NotFound('未找到系统设置，请联系管理员。');
      }
      // 并将数据写入缓存
      await setKey(cacheKey, settings);
    }
    success({
      res,
      data: settings,
    });
  } catch (error) {
    // 返回错误信息
    failure({ res, error });
  }
});

router.put('/', async (req, res) => {
  try {
    const setting = await getList();
    const body = settingsFilterBody(req.body);
    body.updatedAt = new Date();

    await setting.update(body);
    // 删除缓存
    await delKey('setting');
    success({ res, message: '更新成功' });
  } catch (error) {
    failure({ res, error });
  }
});
/**
 * 重建 meilisearch 索引
 * GET /admin/settings/meilisearch_reindex
 */
router.get('/meilisearch_reindex', async function (req, res) {
  try {
    // 课程
    const courses = await Course.findAll({
      attributes: ['id', 'name', 'image', 'content', 'likesCount', 'updatedAt']
    });
    await coursesIndex.addDocuments(courses);

    // 章节
    const chapters = await Chapter.findAll({
      attributes: ['id', 'title', 'content', 'updatedAt'],
      include: [
        {
          model: Course,
          as: 'course',
          attributes: ['id', 'name', 'image']
        }
      ]
    });
    await chaptersIndex.addDocuments(chapters);

    success({ res, message: '重建索引成功。' });
  } catch (error) {
    failure({ res, error });
  }
});
module.exports = router;
